package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class OrderPayListener {

    @Autowired
    private AlipayTemplate alipayTemlate;

    @Autowired
    private OrderService orderService;

    @PostMapping("/payed/notify")
    public String handleAliPay(@RequestBody PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {

        //只有我们确认收到了支付宝的回调并且赶回success,支付宝就再也不通知了
        //验签
        Map<String, String> param = new HashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //解决乱码,这段代码出现乱码的时候使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
            param.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(param, alipayTemlate.getAlipay_public_key(), alipayTemlate.getCharset(), alipayTemlate.getSign_type());

        if (signVerified) {
            String result = orderService.handlePayResult(vo);
            return result;
        } else {
            return "error";
        }
    }
}
